setTimeout(() => {
    document.querySelector("#beibeibeibei-panel > div.titlebar > button.rule").click();
}, 10);

function runWhenDocumentReady(...funcs) {
    const validFuncs = [...new Set(funcs)].filter(item => typeof item === 'function');

    if (document.readyState === 'loading') {
        validFuncs.forEach(func =>
            document.addEventListener('DOMContentLoaded', func)
        );
    } else {
        validFuncs.forEach(func => func());
    }
}

function beibeibeibei_socket() {
    const startButton = document.querySelector("#beibeibeibei-panel .start");
    const testButton = document.querySelector("#beibeibeibei-panel .test");
    const portInput = document.querySelector("#beibeibeibei-panel input.port");
    const pborder = document.querySelector(".beibeibeibei-panel-border");
    const msgContainer = document.querySelector("#beibeibeibei-panel .msgs");
    /** @type {HTMLElement} */
    const led = document.querySelector("#beibeibeibei-panel .led");

    // 获取端口号
    const port = portInput.value.trim();
    // 定义 WebSocket 的 URL
    const wsUrl = `ws://localhost:${port}`;
    // 定义 WebSocket 实例和定时器
    /** @type {WebSocket} */
    let ws;
    let websocketCheckInterval;
    let websocketCheckIntervalTime = 1000;
    let messageCleanupInterval;
    let messageCleanupIntervalTime = 2000;
    // isrunning只是建议启动, 和 WebSocket 状态无关
    let isrunning = false;

    // 启动连接
    startButton.addEventListener("click", () => {
        isrunning = !isrunning;
        // 修改UI
        if (isrunning) {
            startButton.textContent = '停止';
            pborder.classList.add("running");
        } else {
            startButton.textContent = '启动';
            pborder.classList.remove("running");
        }
        // 控制 Websocket
        if (isrunning) {
            // 如果 WebSocket 已经存在, 先关闭它
            if (ws) {
                ws.close();
            }

            // 创建新的 WebSocket 实例
            ws = new WebSocket(wsUrl);

            // 设置定时器, 间隔 intervalTimeout 毫秒检查一次 WebSocket 状态
            websocketCheckInterval = setInterval(() => {
                if (ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) {
                    console.log("WebSocket 状态为 CLOSING 或 CLOSED, 尝试重新连接...");
                    appendMessage("info", `尝试重新连接`);
                    // 关闭当前 WebSocket 实例
                    ws.close();
                    // 创建新的 WebSocket 实例
                    ws = new WebSocket(wsUrl);
                    // 添加 WebSocket 的事件监听
                    ws.onopen = handleWebSocketOpen;
                    ws.onmessage = handleWebSocketMessage;
                    ws.onerror = handleWebSocketError;
                    ws.onclose = handleWebSocketClose;
                }
            }, websocketCheckIntervalTime);

            // 设置定时器, 控制消息容器中的子元素数量
            messageCleanupInterval = setInterval(() => {
                const childrenCount = msgContainer.childElementCount;
                if (childrenCount > 50) {
                    // 计算要删除的前 5% 子元素的数量
                    const deleteCount = Math.ceil(childrenCount * 0.05);
                    // 使用 requestIdleCallback 异步删除前 5% 的子元素
                    requestIdleCallback(() => {
                        for (let i = 0; i < deleteCount; i++) {
                            if (children.length > 0) {
                                msgContainer.removeChild(children[0]);
                            }
                        }
                    });
                }
            }, messageCleanupIntervalTime);

            // 添加 WebSocket 的事件监听
            ws.onopen = handleWebSocketOpen;
            ws.onmessage = handleWebSocketMessage;
            ws.onerror = handleWebSocketError;
            ws.onclose = handleWebSocketClose;
        } else {
            // 停止定时器
            if (websocketCheckInterval) {
                clearInterval(websocketCheckInterval);
                websocketCheckInterval = null;
            }

            // 停止定时器
            if (messageCleanupInterval) {
                clearInterval(messageCleanupInterval);
                messageCleanupInterval = null;
            }

            // 关闭 WebSocket 连接
            if (ws) {
                ws.close();
                ws = null;
            }

            console.log("WebSocket 连接已停止");
        }
    });

    // WebSocket 连接成功
    function handleWebSocketOpen() {
        console.log("WebSocket 连接成功");
        appendMessage("info", `已连接 WebSocket 服务器：${wsUrl}`);
        led.classList.add("websocket-connected");
        led.title = "连接状态: 已连接";
    }

    // WebSocket 收到消息
    function handleWebSocketMessage(event) {
        console.log("收到消息：", event.data);
        appendMessage("msg", event.data);
    }

    // WebSocket 发生错误
    function handleWebSocketError(event) {
        console.log("WebSocket 发生错误：", event);
        appendMessage("error", "WebSocket 连接错误");
    }

    // WebSocket 连接关闭
    function handleWebSocketClose(event) {
        console.log("WebSocket 已关闭");
        appendMessage("info", `WebSocket 连接已断开`);
        led.classList.remove("websocket-connected");
        led.title = "连接状态: 未连接";
    }

    // 测试按钮点击事件
    testButton.addEventListener("click", () => {
        if (ws && ws.readyState === WebSocket.OPEN) {
            // 发送测试消息
            const testMessage = "测试消息";
            ws.send(testMessage);
            appendMessage("info", `已发送测试消息：${testMessage}`);
        } else {
            appendMessage("error", "WebSocket 连接未开启, 无法发送测试消息");
        }
    });

    // 显示消息
    function appendMessage(className, textContent) {
        const msg = document.createElement("p");
        msg.className = className;
        msg.textContent = textContent;
        msgContainer.appendChild(msg);

        // 获取滚动条位置和容器高度信息
        const isNearBottom = msgContainer.scrollTop + msgContainer.clientHeight >= msgContainer.scrollHeight * 0.9;
        // 如果滚动条接近底部，则滚动到底部
        if (isNearBottom) {
            msgContainer.scrollTop = msgContainer.scrollHeight;
        }
    }
}

const gmStorage = {
    rulesData: [
        ['msg1', '', '.test', '无限制', '.test', '0', '旋转'],
        ['msg1', '', '.test', '无限制', '.test', '0', '缩放'],
        ['msg1', '', '.test', '无限制', '.test', '0', '点击']
    ]
};

function GM_setValue(key, value) {
    gmStorage[key] = value;
    console.log("当前gmStorage内容:", JSON.parse(JSON.stringify(gmStorage)));
}
function GM_getValue(key, defaultValue) {
    return gmStorage.hasOwnProperty(key) ? gmStorage[key] : defaultValue;
}

// 保存规则数据
function beibeibeibei_saveRulesData() {
    const bodyElements = document.querySelectorAll('#beibeibeibei-panel-rule-dialog .column.body');
    const savedData = [];

    bodyElements.forEach((element, index) => {
        const children = element.children;
        const rowData = [];
        for (let i = 0; i < children.length; i++) {
            if (i === children.length - 1) {
                // 跳过最后一个包含按钮的div
                continue;
            }
            rowData.push(children[i].textContent.trim());
        }
        savedData.push(rowData);
    });

    GM_setValue('rulesData', savedData);
    console.log('规则数据已保存');
}

// 恢复规则数据
function beibeibeibei_restoreRulesData() {
    const savedData = GM_getValue('rulesData', []);
    const headerElement = document.querySelector('#beibeibeibei-panel-rule-dialog .column.header');
    const addageElement = document.querySelector('#beibeibeibei-panel-rule-dialog .add');
    const bodyElements = document.querySelectorAll('#beibeibeibei-panel-rule-dialog .column.body');

    // 清除现有的body元素
    bodyElements.forEach(element => {
        element.remove();
    });

    // 恢复保存的内容
    savedData.forEach((rowData, index) => {
        const newBody = document.createElement('div');
        newBody.className = 'column body';
        newBody.dataset.index = index;

        rowData.forEach((data) => {
            const div = document.createElement('div');
            div.textContent = data;
            newBody.appendChild(div);
        });

        // 添加删除按钮
        const deleteDiv = document.createElement('div');
        const delBtn = document.createElement('button');
        delBtn.className = 'remove';
        delBtn.textContent = '删除此条';
        delBtn.type = 'button';
        delBtn.onclick = function () {
            const bodyElement = this.closest('.column.body');
            const index = bodyElement.dataset.index;
            // 从页面中删除元素
            bodyElement.remove();
            // 从存储的数据中删除对应条目
            const savedData = GM_getValue('rulesData', []);
            savedData.splice(index, 1);
            GM_setValue('rulesData', savedData);
        };
        deleteDiv.appendChild(delBtn);
        newBody.appendChild(deleteDiv);

        // 插入到header和add按钮之间
        headerElement.parentNode.insertBefore(newBody, addageElement);
    });
}

runWhenDocumentReady(beibeibeibei_socket, beibeibeibei_restoreRulesData);
